package lincen.javase.util.array;

import java.util.List;

/**
 * 数组工具
 * @author 	林岑
 * @time	2012年3月23日 14:50:43
 *
 */
public class ArrayUtil {

	/**
	 * 判断数组中所有元素是否相等
	 * @param suitNo
	 * @return
	 */
	public static boolean allIsTheSame(int... suitNo) {
		for (int i = 0; i < suitNo.length - 1; i++) {
			if(suitNo[i] != suitNo[i + 1]) {
				return false;
			}
		}
		return true;
	}
	
	/**
	 * 将一个逗号分隔的字符串列表转换为整型数组<br>
	 * 前提intList格式合法.<br>
	 * 比如 1111,213,646,674987,16546,333<br>
	 * 	   
	 * 将用逗号分隔的int字符串, 转换成int数组<br>
	 * <br>
	 * 如果其中有空白, 那么那个值就等于 -1<br>
	 *  1111,213,646,,16546,333 	------>  1111,213,646,-1,16546,333
	 *  1111,213,646,,16546,333, 	------>  1111,213,646,-1,16546,333,-1
	 */
	public static int [] asArray(String intList) {

		if(intList == null || intList.equals("")){
			return new int[0];
		}

		intList = intList.replaceAll(",,", ",-1,");
		intList = intList.endsWith(",") ? intList += "-1" : intList;
		String [] idListString = intList.split( "," );
		int [] r = new int[idListString.length];
		for (int i = 0; i < r.length; i++) {
			if(idListString[i].equals("")) {
				r[i] = -1;
			} else {
				r[i] = Integer.parseInt(idListString[i].trim());
			}
		}
		return r;

	}
	

	/**
	 * 计算数组前n项和
	 * @param is		被计算数组
	 * @param n			前n项
	 * @return			前n项和
	 */
	public static int sumOfSubArray ( int[] is, int n ) {
		int sum = 0;
		for (int i = 0; i < n; i++) {
			sum += is[i];
		}
		return sum;
	}
	
	/**
	 * 将整型数值列表转成字符串形式, 以逗号分隔
	 * @param idList
	 * @return
	 */
	public static String toStringSplitByComma(List<Integer> idList) {
		if(idList == null || idList.size() == 0) {
			return "";
		}
		String temp = "";
		for (int i = 0; i < idList.size(); i++) {
			Integer id = idList.get( i );
			if(i == 0) {
				temp += id;
			} else {
				temp += "," + id;
			}
		}
		return temp;
	}
}
